package cn.tedu.boot34.controller;

import cn.tedu.boot34.entity.User;
import cn.tedu.boot34.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
public class UserController {
    @Autowired(required = false)
    UserMapper mapper;
    @RequestMapping("/reg")
    public String reg(User user){
        mapper.insert(user);
        return "注册成功!";
    }
    @RequestMapping("/login")
    public String login(User user, HttpServletResponse response) throws IOException {
        //通过用户名查询出数据库中对应的用户对象
        User u = mapper.login(user.getUsername());
        //判断是否查询到了用户名对应的用户,如果没查到说明用户不存在
        if (u!=null){
            //拿用户输入的密码和查询到的密码作比较
            if (user.getPassword().equals(u.getPassword())){
                //登录成功 重定向到列表页面
                response.sendRedirect("/select");
                return null;
            }
            return "密码错误!";
        }


       return "用户不存在!";
    }

    @RequestMapping("/select")
    public String select(){
        List<User> list = mapper.selectAll();
        String html = "<table border='1'>";
        html+="<caption>用户列表</caption>";
        html+="<tr><th>id</th><th>用户名</th><th>密码</th><th>操作</th></tr>";
        //遍历集合
        for (User u:list) {
            html+="<tr>";
            html+="<td>"+u.getId()+"</td>";
            html+="<td>"+u.getUsername()+"</td>";
            html+="<td>"+u.getPassword()+"</td>";
            html+="<td><a href='/delete?id="+u.getId()+"'>删除</a></td>";
            html+="</tr>";
        }
        html+="</table>";
        return html;

    }

    @RequestMapping("/delete")
    public void delete(int id,HttpServletResponse response) throws IOException {
        mapper.delete(id);
        //重定向到列表页面
        response.sendRedirect("/select");

    }
}
